import { Router } from '@zh/common-utils/router'
import builder from '@zh/common-utils/router/route-generator'

import { store } from './store'

import { RouteView, BasicLayout, MultiTabRouteView } from './layouts'
import NProgress from 'nprogress'
import './components/NProgress/nprogress.less'

import { getLoginUser } from './api/user/index'
import { getUserMenu } from './api/auth/index'
import { get as getThemes } from './api/themes/index'
import { cloneDeep } from 'lodash'

// 扩展router实现方法
import RouterImpl from './router-impl'

NProgress.configure({ showSpinner: false })

let router = null

const microAppConfigs = {}

const install = (Vue) => {
  if (install.installed) {
    return
  }

  router = new Router(Vue, store)

  Vue.use(RouterImpl, router)

  /**
   * 配置加载进度条
   */
  router.onBeforeEach = (to, from, next) => {
    NProgress.start()
  }

  router.onAfterEach = () => {
    NProgress.done()
  }

  // 路由拦截，给页面组件注入 name 属性
  router.beforeResolve((to, from, next) => {
    const cmp = [...to.matched].pop()?.components?.default
    cmp && (cmp._Ctor[0].options.name = to.fullPath)
    next()
  })

  router.afterInitUserInfo = () => {
    return new Promise((resolve, reject) => {
      resolve()
    })
  }

  /**
   * 配置登录信息
   */
  router.onNeedLoginInfo = () => {
    return new Promise((resolve, reject) => {
      // 本地缓存没有用户信息则从服务端获取
      getLoginUser(true, false).then(info => {
        if (!info.agent) {
          info.agent = false
        }
        store.setLoginUser(info)
        // 获取主题
        if (process.env.VUE_APP_ENABLE_THEMES_SETTING === 'true') {
          getThemes().then(response => {
            store.setThemes(Object.assign(store.getThemes(), response || {}))
          })
        }
        // 获取菜单
        getUserMenu().then(response => {
          const { rootList, menuList, menuMap } = builder(response, router)
          store.setMenu(menuList, menuMap)
          router.afterDynamicRoutesBuild(rootList)
          rootList.map(root => {
            router.addRoute(root)
          })
          router.afterInitUserInfo().then(() => {
            resolve()
          })
        })
      }).catch(e => {
        reject(e)
      })
    })
  }

  router.setMicroAppConfig = (name, options) => {
    microAppConfigs[name] = options
  }

  router.getMicroAppConfig = (name) => {
    if (!microAppConfigs[name]) {
      router.setMicroAppConfig(name)
    }
    return microAppConfigs[name]
  }

  /**
   * 配置默认根路由
   */
  router.setRoots([{
    path: '/',
    name: 'root',
    component: BasicLayout
  }])

  // 加载路由配置
  router.loadRouteConfigFiles(require.context('./routes', true, /\.js$/), 'pc')

  // 加载移动端路由配置
  // router.loadRouteConfigFiles(require.context('./routes-mobile', true, /\.js$/), 'mobile')
}

export { router }

export default {
  install
}
